<?php

namespace app\api\service;


use app\common\energyApi\Energy;
use app\common\model\tang\Cost;
use app\common\model\tang\CostType;
use app\common\model\tang\Invoice;
use app\common\model\tang\Merchant;
use app\common\model\tang\WatchMaintain;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;
use think\queue\Job;
use think\cache\driver\Redis;

class Jobs
{
    public function cost(Job $job, $data)
    {
        $isJobDone = $this->_doTaskA($data);
        if ($isJobDone) {
            echo '删除cost';
            $job->delete();
        } else {
            if ($job->attempts() > 3) {
                $job->delete();
            }
        }
    }
    /**
     * @param array $info
     * @return bool|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function _doTaskA(array $info)
    {
        $HDService = new HaiDing();
        $merchantInfo = new  Merchant();
        $costInfo = new  Cost();
        $result = $HDService->getCostUrl('',$info['order_id'],'',0,1000);
        foreach ($result as $k=>$v) {
            $mch_id = $merchantInfo->where('code', $v['contract']['code'])->value('id');
            foreach ($v['subjects'] as $ks => $vs) {
                $cost = [];
                $cost['billid'] = $vs['accId'];
                $cost['cost_name'] = $vs['subject']['name'];
                $cost['cost_code'] = $vs['subject']['code'];
                $cost['all_amount'] = $vs['payTotal'] * 100;//应收金额
                $cost['amount'] = $vs['unpayedTotal'] * 100;//待支付金额
                $cost['pay_amount'] = $vs['payedTotal'] * 100; //已收金额
                $cost['real_amount'] = $vs['unpayedTotal'] * 100;
                $cost['statment_uuid'] = $v['statmentUuid'];//账单id
                $cost['billNubmer'] = $v['billNumber'];//账单id
                $cost['date_type'] = 1;
                $cost['start_time'] = strtotime($vs['beginDate']);
                $cost['end_time'] = strtotime($vs['endDate']);
                $cost['contract_uuid'] = $v['contract']['uuid'];
                $cost['contract_code'] = $v['contract']['code'];
                $isfirst = $costInfo->where('billid', $vs['accId'])->find();
                if ($isfirst) { //此处只做更新
                    $cost['merchant_id'] = $mch_id;
                    if($vs['unpayedTotal']==0&&$isfirst['pay_status']==0){
                        $cost['pay_status']=1;
                        if(empty($isfirst['bill_no'])){
                            $cost['pay_time']=date('Y-m-d H:i:s');
                            $cost['bill_no'] = $this->getBill();
                        }
                    }
                    $costInfo->where('billid', $vs['accId'])->update($cost);
                }
            }
        }
        return true;
    }
    public function getBill()
    {
        $redis = (new Redis(config('queue.connections.redis')));
        $count = $redis->llen('HFZD' . date('Ymd'));
        $redis->delete('HFZD' . date('Ymd', strtotime('-1 day')));
        if ($count == 0) {
            for ($i = 99999; $i >= 0; $i--) {
                $jh = str_pad($i, 5, "0", STR_PAD_LEFT);
                $redis->lPush('HFZD' . date('Ymd'), $jh);
            }
        }
        $time = date('Ymd', time());
        $bill = 'HFZD' . $time . $redis->lpop('HFZD' . date('Ymd'));
        return $bill;
    }
    public function OrderSn()
    {
        $OrderSn = 'T' . date('Ymd', time()) . rand(10000, 99999);
        $model = new \app\common\model\tang\Cost();
        $is_sn = $model->where('order_sn', $OrderSn)->find();
        if ($is_sn) {
            $this->OrderSn();
        }
        return $OrderSn;
    }

    /**
     * 更新电表
     */
    public function PointName(Job $job, $data)
    {
        $isJobDone = $this->_doPointName($data);
        if ($isJobDone) {
            echo '删除数据';
            $job->delete();
        } else {
            if ($job->attempts() > 3) {
                $job->delete();
            }
        }
    }
    public function _doPointName(array $info){
        $Energy = new Energy();
        $WatchMaintain = new WatchMaintain();
        $data = [
            "pointId" => $info['pointId'],
            "monthTime" => date('Y-m', strtotime('-1 month')) // 月份
        ];
        // 查询月电费接口
        //query_YWGPointPowerUsed_info 电
        //query_YWGPointWaterUsed_info

        if($info['type']==1){
            $port_data = $Energy->universalfunction('query_YWGPointPowerUsed_info', $data);
        }else{
            $port_data = $Energy->universalfunction('query_YWGPointWaterUsed_info', $data);
        }

        if(isset($port_data)&&!empty($port_data)){
//            $pointInfo = $WatchMaintain->where(['userId'=>$info['userId'],'type'=>$info['type']])->find();

          $WatchMaintain->where(['pointId'=>$info['pointId']])->update(['pointName'=>$port_data['pointName']]);
        }
        return true;

    }

}